package com.itheima.controller;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        //resp.setContentType("text/html;charset=utf-8");  //可以的
        resp.setContentType("application/json;charset=utf-8");  //标准
        //2 获取请求参数
        String username = req.getParameter("username");
        //3 调用service层方法，查询用户信息List<User>
        UserService userService = new UserServiceImpl();
        List<User> list = userService.selectLike(username);
        //4 将用户信息转换成json发送给客户端
        ObjectMapper objectMapper = new ObjectMapper();
        /*String json = objectMapper.writeValueAsString(list);
        resp.getWriter().write(json);*/
        //将list集合转换成json，然后通过参数1的流对象输出。
        objectMapper.writeValue(resp.getWriter(), list);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
